import {
  config
} from '../config.js'

const tips = {
  1: '没网！！！',
  1000: '输入参数错误',
  1005: '不正确的开发者key',
  1007: '未找到当前接口',
  0: '点赞成功'
}

export class HTTP {
  request(parames) {
    if (!parames.method) {
      parames.method = "POST"
    }
    let id = wx.getStorageSync('id')
    parames.data.unid = id
      wx.request({
        url: config.url + parames.url,
        method: parames.method,
        header: {
          //"content-type": "application/x-www-form-urlencoded",
          // 'content.-type': 'application/json',
          // 'appkey': config.appkey
        },
        data: parames.data,
        success: (res) => {
          
          // startsWith endsWith 字符串开头 结尾
          parames.success(res)
        },
        fail: (err) => {
          console.log(err)
          // this._show_error(1)
        }
      })
      //console.log(parames)
    }
  _show_error(error_code) {
    // console.log(error_code)
    if (!error_code) {
      error_code = 1
    }
    wx.showToast({
      title: tips[error_code],
      icon: 'none',
      duration: 2000,
    })

  }

  jump(parames) {
    //console.log(parames)
    let method = parames.method ? parames.method : 'navigateTo'
    let aa = wx.getStorageSync('info')
    // console.log('aa')
    // console.log(parames)
    let url
    if (!aa.userInfo) {
      url = '/pages/authorize/index'
    } else {
      url = parames.url
    }

    //拨打电话
    if (url.indexOf('tel:') > -1) {
      wx.makePhoneCall({
        phoneNumber: url.split(':')[1],
      })
    } else
      //网页跳转
      if (url.indexOf('http') > -1) {
        // console.log(url)
        wx.navigateTo({
          url: `/pages/new/index?src=${url}`,
        })
      } else {
        wx[method]({
          url: url,
          success: (res) => {
            // startsWith endsWith 字符串开头 结尾
            parames.success ? parames.success(res) : ''
          }
        })
      }

  }

  throttle(fn, gapTime) {
    if (gapTime == null || gapTime == undefined) {
      gapTime = 1500
    }

    let _lastTime = null

    // 返回新的函数
    return function() {
      let _nowTime = +new Date()
      if (_nowTime - _lastTime > gapTime || !_lastTime) {
        fn.apply(this, arguments) //将this和参数传给原函数
        _lastTime = _nowTime
      }
    }
  }


}